package com.cait.dutyfree.action.impl;

/**
 * @author Nandun Madhura
 * 
 *
 */
import java.util.Date;
import java.util.Properties;
import java.util.Random;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.cait.dutyfree.dataaccess.CustomerServiceDao;
import com.cait.dutyfree.dataaccess.UserServiceDAO;
import com.cait.dutyfree.pojo.Customer;
import com.cait.dutyfree.pojo.LoginUser;
import com.cait.dutyfree.security.Password;
import com.opensymphony.xwork2.ActionSupport;

public class CustomerAction extends ActionSupport {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Customer customer;
	private UserServiceDAO userServiceDAO;
	private CustomerServiceDao customerservicedao;
	public static final String MAIL_SERVER = "smtp.gmail.com";
	public static final String USERNAME = "dfassnandun@gmail.com";
	public static final String PASSWORD = "dfass@123";

	public CustomerAction(Customer customer,
			CustomerServiceDao customerservicedao, UserServiceDAO userServiceDAO) {
		this.setCustomer(customer);
		this.setCustomerservicedao(customerservicedao);
		this.setUserServiceDAO(userServiceDAO);

	}

	public String execute() throws Exception {
		// System.out.println("aaaaaaaaaaaaaa"+getCustomer().getCusid()+"bbbbbbbb");

		LoginUser user = new LoginUser();
		// boolean isValidForm = true;
		Password p = new Password("onlykalu");

		user.setfName(customer.getFirstname());
		user.setUsername(customer.getUsername());
		user.setEmail(customer.getEmail());
		// user.setlName(getlName());
		// user.setAddress(getAddress());
		// user.setContactNo(getTeleNo());
		// user.setMobileNo(getMobileNo());
		user.setCreatedDate(new Date());
		user.setStatus(0);
		String validChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
		String psw = "";

		Random generator = new Random();
		for (int i = 0; i < 12; i++) {
			psw += validChars.charAt(generator.nextInt(validChars.length()));
		}

		System.out.println(psw);
		user.setPassword(p.encrypt(psw));
		getCustomer().setPassword(psw);

		// System.out.println(customer.getUserName()+" trrrrrrr"+user.getStatus()+" "+p.encrypt(customer.getPasswrd().trim())+" "+customer.getPasswrd().trim());

		if (getCustomerservicedao().save(getCustomer()) == 0) {
			try {
				if (!getUserServiceDAO().isUserAvailable(
						getCustomer().getUsername().trim())) {
					getUserServiceDAO().addUser(user);

					if (sendMail() != 0) {
						addActionMessage("Error occured check you internet connection");
						return ERROR;
					}
					addActionMessage("Record added successfully.");

					return SUCCESS;
				} else {
					addActionMessage("Username already exists");
					return ERROR;
				}

			} catch (Exception e) {
				addActionMessage("Username already exists");
				System.out.println(e);
				return ERROR;
			}

		} else {
			addActionError("Record adding failed.");
			return ERROR;
		}

	}

	public void setCustomer(Customer customer) {
		this.customer = customer;
	}

	public Customer getCustomer() {
		return customer;
	}

	public void setCustomerservicedao(CustomerServiceDao customerservicedao) {
		this.customerservicedao = customerservicedao;
	}

	public CustomerServiceDao getCustomerservicedao() {
		return customerservicedao;
	}

	public int sendMail() {

		try {
			String fromAddress = "admin@dfas.com";
			String toAddress = getCustomer().getEmail();
			String subject = "Login Details";
			String message = "Hi " + getCustomer().getFirstname()
					+ "\n\r yor user name : " + getCustomer().getUsername()
					+ "\n\r Password: " + getCustomer().getPassword();

			Properties properties = System.getProperties();
			properties.put("mail.smtps.host", MAIL_SERVER);
			properties.put("mail.smtps.auth", "true");

			Session session = Session.getInstance(properties);
			MimeMessage msg = new MimeMessage(session);

			msg.setFrom(new InternetAddress(fromAddress));
			msg.addRecipients(Message.RecipientType.TO, toAddress);
			msg.setSubject(subject);
			msg.setText(message);

			Transport tr = session.getTransport("smtps");
			tr.connect(MAIL_SERVER, USERNAME, PASSWORD);
			tr.sendMessage(msg, msg.getAllRecipients());

			tr.close();
			return 0;
		} catch (AddressException ex) {
			System.out.println(ex.getMessage());
			return 1;
		} catch (MessagingException ex) {
			System.out.println(ex.getMessage());
			return 1;
		}
	}

	public void setUserServiceDAO(UserServiceDAO userServiceDAO) {
		this.userServiceDAO = userServiceDAO;
	}

	public UserServiceDAO getUserServiceDAO() {
		return userServiceDAO;
	}

}
